package ace.module.upms.core.impl.service.impl;

import ace.cmp.core.enums.SystemCodeEnum;
import ace.cmp.core.model.R;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceUserInfoDto;
import ace.module.oauth2.server.api.model.dto.ext.Oauth2AceUserInfoResultDto;
import ace.module.oauth2.server.api.callback.model.input.Oauth2AceAuthorizationCallbackInput;
import ace.module.upms.core.impl.service.UmpsAuthorityService;
import ace.module.upms.core.impl.service.UpmsOauth2Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/3/18 16:16
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class UpmsOauth2ServiceImpl implements UpmsOauth2Service {
  private final UmpsAuthorityService umpsAuthorityService;

  @Override
  public Oauth2AceUserInfoResultDto getOauth2UserInfo(
      Long upmsAppId, Oauth2AceAuthorizationCallbackInput request) {
    String accountIdString = request.getAccountId();
    Long accountId = Long.parseLong(accountIdString);

    Set<String> authorities = umpsAuthorityService.getByUpmsAppIdAndAccountId(upmsAppId, accountId);
    Map<String, String> attributes = new HashMap<>();
    return this.buildOAuth2UserInfoResultDto(accountIdString, attributes, authorities);
  }

  private Oauth2AceUserInfoResultDto buildOAuth2UserInfoResultDto(
      String accountId, Map<String, String> attributes, Set<String> authorities) {
    Oauth2AceUserInfoResultDto resultDto = new Oauth2AceUserInfoResultDto();
    resultDto.setCode(R.OK);
    resultDto.setMessage(SystemCodeEnum.SUCCESS.getDesc());
    resultDto.setData(
        Oauth2AceUserInfoDto.builder()
            .id(accountId)
            .attributes(attributes)
            .authorities(authorities)
            .build());

    return resultDto;
  }
}
